/*
 Copyright 2010 Victor Mayoral Vilches
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


//
//  MotionViewController.m
//  NaoRemote
//
//  Created by Victor Mayoral Vilches on 23/11/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "MotionViewController.h"
#import "PruebaView.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <CoreGraphics/CoreGraphics.h>
#import "PresentacionViewController.h"

#define PORT "54010" // default the port client will be connecting to 
#define MAXDATASIZE 100 // max number of bytes we can get at once 
#define MAXIMAGESIZE 500000 // max number of bytes we can get at once 


#define VIDEO_ON "1"
#define VIDEO_OFF "0"

@implementation MotionViewController

@synthesize subview;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
    }
    return self;
}



/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */

#pragma mark -
#pragma mark Comprobacion Conectividad


- (void)alertSimpleAction: (NSString*) mensaje
{
	// open an alert with just an OK button
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Conectividad" message:mensaje
                                                   delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
	[alert show];	
	[alert release];
}


- (void) proccessReachability: (Reachability*) curReach
{
    NetworkStatus netStatus = [curReach currentReachabilityStatus];
    BOOL connectionRequired= [curReach connectionRequired];
    NSString* statusString= @"";
    switch (netStatus)
    {
        case NotReachable:
        {
            statusString = @"Access Not Available";
            //Minor interface detail- connectionRequired may return yes, even when the host is unreachable.  We cover that up here...
            connectionRequired= YES;  
            break;
        }
            
        case ReachableViaWWAN:
        {
            statusString = @"Reachable WWAN";
            break;
        }
        case ReachableViaWiFi:
        {
            statusString= @"Reachable WiFi";
            break;
        }
    }
    if(connectionRequired)
    {
        statusString= [NSString stringWithFormat: @"%@, Connection Required", statusString];
    }
    [self alertSimpleAction:statusString];
    //Una vez hemos determinado en que caso nos encontramos generamos un AlertView

}




- (void) updateInterfaceWithReachability: (Reachability*) curReach
{
    if(curReach == hostReach)
	{
        NetworkStatus netStatus = [curReach currentReachabilityStatus];
        BOOL connectionRequired= [curReach connectionRequired];
        
        NSString* baseLabel=  @"";
        if(connectionRequired)
        {
            baseLabel=  @"Cellular data network is available.\n  Internet traffic will be routed through it after a connection is established.";
        }
        else
        {
            baseLabel=  @"Cellular data network is active.\n  Internet traffic will be routed through it.";
        }
        NSLog(baseLabel);
		[self proccessReachability:curReach];
    }
    //	if(curReach == internetReach)
    //	{	
    //		[self proccessReachability:curReach];
    //	}
    
    //	if(curReach == wifiReach)
    //	{	
    //        [self proccessReachability:curReach];
    //	}
	
}


////Called by Reachability whenever status changes.
//- (void) reachabilityChanged: (NSNotification* )note
//{
//	Reachability* curReach = [note object];
//	NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
//	[self updateInterfaceWithReachability: curReach];
//}

- (IBAction)comprobarConectividad:(id)sender{
	hostReach = [[Reachability reachabilityWithHostName: ip.text] retain];
	[hostReach startNotifer];
	[self updateInterfaceWithReachability: hostReach];
    
}

#pragma mark -

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    
    videoEstate = VIDEO_OFF;
    ip.keyboardType = UIKeyboardTypeDefault;	// use the default type input method (entire keyboard)
    ip.returnKeyType = UIReturnKeyDone;    
    ip.clearButtonMode = UITextFieldViewModeWhileEditing;	// has a clear 'x' button to the right        
    ip.delegate = self;	// let us be the delegate so we know when the keyboard's "Done" 
    //    ip.placeholder = @"dirección ip";
    
    puerto.keyboardType = UIKeyboardTypeDefault;	// use the default type input method (entire keyboard)
    puerto.returnKeyType = UIReturnKeyDone;    
    puerto.clearButtonMode = UITextFieldViewModeWhileEditing;	// has a clear 'x' button to the right        
    puerto.delegate = self;	// let us be the delegate so we know when the keyboard's "Done" 
    //    puerto.placeholder = @"puerto";    

    
/*
 ////////////////////////////////////////////////////////////////////////////////////////
 CONFIGURACIÓN DEL TEST DE CONECTIVIDAD
 ////////////////////////////////////////////////////////////////////////////////////////
 */
//    // Observe the kNetworkReachabilityChangedNotification. When that notification is posted, the
//    // method "reachabilityChanged" will be called. 
//    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
    
    //    //Change the host name here to change the server your monitoring
    //    remoteHostLabel.text = [NSString stringWithFormat: @"Remote Host: %@", @"www.urjc.es"];
//	hostReach = [[Reachability reachabilityWithHostName: ip.text] retain];
////	[hostReach startNotifer];
//	[self updateInterfaceWithReachability: hostReach];
	
    //    internetReach = [[Reachability reachabilityForInternetConnection] retain];
    //	[internetReach startNotifer];
    //	[self updateInterfaceWithReachability: internetReach];
    
    //    wifiReach = [[Reachability reachabilityForLocalWiFi] retain];
    //	[wifiReach startNotifer];
    //	[self updateInterfaceWithReachability: wifiReach];
    
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return YES;
}


//- (void)didRotateFromInterfaceOrientation: 
//(UIInterfaceOrientation)fromInterfaceOrientation 
//{ 
//    /* Add post-orientation change code here */ 
//    if fromInterfaceOrientation
//        ip.text = @"chupame un pie";
//}


- (void)willRotateToInterfaceOrientation: 
(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration  { 
    if ((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight)) {
        walkButton.hidden = YES;
        etiq1.hidden = YES;
        textView.hidden = YES;
        ip.hidden = YES;
        puerto.hidden = YES;
        ip_label.hidden = YES;
        puerto_label.hidden = YES;
        
        walkButtonLandscape.hidden = NO;
        turnLeftButtonLandscape.hidden = NO;
        turnRightButtonLandscape.hidden = NO;
        imagen.hidden = NO;
        video.hidden = NO;
    }
    else{
        walkButton.hidden = NO;
        etiq1.hidden = NO;
        textView.hidden = NO;
        ip.hidden = NO;
        puerto.hidden = NO;
        ip_label.hidden = NO;
        puerto_label.hidden = NO;
        
        
        walkButtonLandscape.hidden = YES;
        turnLeftButtonLandscape.hidden = YES;
        turnRightButtonLandscape.hidden = YES;                
        imagen.hidden = YES;
        video.hidden = YES;
    }
}  


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

//
//#pragma mark -
//#pragma mark Conexion TCP
//
//
//// get sockaddr, IPv4 or IPv6:
//void *get_in_addr(struct sockaddr *sa)
//{
//    if (sa->sa_family == AF_INET) {
//        return &(((struct sockaddr_in*)sa)->sin_addr);
//    }
//    
//    return &(((struct sockaddr_in6*)sa)->sin6_addr);
//}
//
//
//
//void sendMessage(char * linea, char * ip_cadena, char * port_cadena){
//        
//    //Declaración de variables	
//    int sockfd, numbytes;  
//    char buf[MAXDATASIZE];
//    struct addrinfo hints, *servinfo, *p;
//    int rv;
//    char s[INET6_ADDRSTRLEN];
//    int bytes_sent;
//    char mensaje[50];
//    
//    
//    printf("Trying to conect to: %s at port %s \n",ip_cadena, port_cadena);
//    
//    //Formamos el struct hints
//    memset(&hints, 0, sizeof hints);
//    hints.ai_family = AF_UNSPEC;
//    hints.ai_socktype = SOCK_STREAM;
//    
//    if ((rv = getaddrinfo(ip_cadena, port_cadena, &hints, &servinfo)) != 0) {
//        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
//        return;
//    }
//    
//    // loop through all the results and connect to the first we can
//    for(p = servinfo; p != NULL; p = p->ai_next) {
//        if ((sockfd = socket(p->ai_family, p->ai_socktype,
//                             p->ai_protocol)) == -1) {
//            perror("client: socket");
//            continue;
//        }
//        
//        if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
//            close(sockfd);
//            perror("client: connect");
//            continue;
//        }
//        
//        break;
//    }
//    
//    if (p == NULL) {
//        fprintf(stderr, "client: failed to connect\n");
//        return;
//    }
//    
//    inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
//              s, sizeof s);
//    
//    //----------------------------------------------------------------
//    //				SEND		WALK    MESSAGE
//    //----------------------------------------------------------------
//    
//    printf("client: connecting to %s\n", s);    
//    
//    if (bytes_sent = send(sockfd, linea, sizeof(mensaje), 0) == -1) 
//        perror("send"); 				
//    
//    //	Writeline(sockfd, mensaje, sizeof(mensaje));	
//    
//    //----------------------------------------------------------------
//    //----------------------------------------------------------------
//    
//    
//    //freeaddrinfo(servinfo); // all done with this structure
//    
//    if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
//        perror("recv");
//        exit(1);
//    }
//    
//    buf[numbytes] = '\0';
//    
//    printf("client: received '%s'\n",buf);
//    close(sockfd);            
//}
//
//char* askForImage(char * ip_cadena, char * port_cadena)
//{
//    
//    //---------------------------------------------------------------------------
//    //                  RECEPCIÓN DEL ARRAY DE BYTES
//    //---------------------------------------------------------------------------
//    
//    //Lo primer es conectarnos con el servidor y hacer la petición de la imagen
//    
//    char * linea = "image";
//    
//    //Declaración de variables	
//    int sockfd, numbytes;  
//    Byte buf[MAXIMAGESIZE];
//    struct addrinfo hints, *servinfo, *p;
//    int rv;
//    char s[INET6_ADDRSTRLEN];
//    int bytes_sent;
//    char mensaje[50];
//    
//    printf("Trying to conect to: %s at port %s \n",ip_cadena, port_cadena);
//    
//    //Formamos el struct hints
//    memset(&hints, 0, sizeof hints);
//    hints.ai_family = AF_UNSPEC;
//    hints.ai_socktype = SOCK_STREAM;
//    
//    // This function helps set up the structs you need later on.
//    if ((rv = getaddrinfo(ip_cadena, port_cadena, &hints, &servinfo)) != 0) {
//        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
//        return nil;
//    }
//    
//    // loop through all the results and connect to the first we can
//    for(p = servinfo; p != NULL; p = p->ai_next) {
//        if ((sockfd = socket(p->ai_family, p->ai_socktype,
//                             p->ai_protocol)) == -1) {
//            perror("client: socket");
//            continue;
//        }
//        
//        if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
//            close(sockfd);
//            perror("client: connect");
//            continue;
//        }
//        
//        break;
//    }
//    
//    if (p == NULL) {
//        fprintf(stderr, "client: failed to connect\n");
//        return NULL;
//    }
//    
//    inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
//              s, sizeof s);
//    
//    
//    
//    printf("client: connecting to %s\n", s);    
//    
//    if (bytes_sent = send(sockfd, linea, sizeof(mensaje), 0) == -1) 
//        perror("send"); 				
//    
//    
//    
//    // ESPERAMOS RECIBIR LA RESPUESTA
//
//    //freeaddrinfo(servinfo); // all done with this structure
//    
//    //    sockfd is the socket descriptor to read from, buf is the buffer to read the information into, len is 
//    //    the maximum length of the buffer, and flags can again be set to 0. (See the recv() man page for flag 
//    //                                                                        information.) 
//    //    recv() returns the number of bytes actually read into the buffer, or -1 on error (with errno set, 
//    //                                                                                      accordingly.) 
//    //    Wait! recv() can return 0. This can mean only one thing: the remote side has closed the connection 
//    //    on you! A return value of  is 's way of letting you know this has occurred. 
//    
//    int bytes_recibidos = 0;
//    void *aux;
//    aux = buf;
//
//    //Recibimos los bytes en el buffer
//    while (bytes_recibidos < 230400) {
//        if ((numbytes = recv(sockfd, aux, MAXIMAGESIZE, 0)) == -1) {
//            perror("recv");
//            exit(1);
//        }else{
//            bytes_recibidos += numbytes;
//            aux = &buf[bytes_recibidos];
//        }
//        
//    }
//
//    printf("client: received '%i'\n",bytes_recibidos);
//
//    
//    int pixelsWide = 320;
//    int pixelsHigh = 240;
//    char* buffer = malloc(pixelsHigh*pixelsWide*3);
//    
//    //Una vez recibidos los bytes los copiamos un char* que lo que devolveremos
//    for (int i=0; i<pixelsHigh*pixelsWide*3; i++) {
//        buffer[i] = buf[i];
//    }
//    
//    close(sockfd);
//    return buffer;
//}
//
//#pragma mark -
//#pragma mark Acciones Interfaz
//
//
/*
 Metodo de saludo al robot
 
 */
- (IBAction)helloButton:(id)sender{

    NSLog(@"Se ha presionado el botón de hello");
    char * linea = "hello";
    //    NSString *server_ip = [[NSUserDefaults standardUserDefaults] stringForKey:@"server_ip"];
    //    NSString *server_port = [[NSUserDefaults standardUserDefaults] stringForKey:@"server_port"];    
    NSString *server_ip = ip.text;
    NSString *server_port = puerto.text;
    
    //    NSLog(server_ip);
    //    NSLog(server_port);
    
    //Forma de convertir NSString a char *
    const char *ip_cadena = [server_ip UTF8String];
    const char *port_cadena = [server_port UTF8String];
    
    sendMessage(linea,ip_cadena, port_cadena);
    
}    
//
///*
// Metodo que hace que el robot ande en linea recta
// */
//- (IBAction)walkButton:(id)sender{
//    NSLog(@"Se ha presionado el botón de walk");
//    char * linea = "walk";
//    //    NSString *server_ip = [[NSUserDefaults standardUserDefaults] stringForKey:@"server_ip"];
//    //    NSString *server_port = [[NSUserDefaults standardUserDefaults] stringForKey:@"server_port"];    
//    
//    NSString *server_ip = ip.text;
//    NSString *server_port = puerto.text;
//    
//    //    NSLog(server_ip);
//    //    NSLog(server_port);
//    
//    //Forma de convertir NSString a char *
//    const char *ip_cadena = [server_ip UTF8String];
//    const char *port_cadena = [server_port UTF8String];
//    sendMessage(linea,ip_cadena, port_cadena);
//}
//
//
///*
// Metodo para hacer que el robot gire hacia la derecha
// 
// */
//
//
//- (IBAction)turnRightButton:(id)sender{
//    NSLog(@"Se ha presionado el botón de turnright");
//    char * linea = "turnright";
//    //    NSString *server_ip = [[NSUserDefaults standardUserDefaults] stringForKey:@"server_ip"];
//    //    NSString *server_port = [[NSUserDefaults standardUserDefaults] stringForKey:@"server_port"];    
//    NSString *server_ip = ip.text;
//    NSString *server_port = puerto.text;
//    
//    //    NSLog(server_ip);
//    //    NSLog(server_port);
//    
//    //Forma de convertir NSString a char *
//    const char *ip_cadena = [server_ip UTF8String];
//    const char *port_cadena = [server_port UTF8String];
//    
//    sendMessage(linea,ip_cadena, port_cadena);
//    
//}
//
///*
// Metodo para hacer que el robot gire hacia la izquierda
// 
// */
//- (IBAction)turnLeftButton:(id)sender{
//    NSLog(@"Se ha presionado el botón de turnleft");
//    char * linea = "turnleft";
//    //    NSString *server_ip = [[NSUserDefaults standardUserDefaults] stringForKey:@"server_ip"];
//    //    NSString *server_port = [[NSUserDefaults standardUserDefaults] stringForKey:@"server_port"];    
//    NSString *server_ip = ip.text;
//    NSString *server_port = puerto.text;
//    
//    //    NSLog(server_ip);
//    //    NSLog(server_port);
//    
//    //Forma de convertir NSString a char *
//    const char *ip_cadena = [server_ip UTF8String];
//    const char *port_cadena = [server_port UTF8String];
//    
//    sendMessage(linea,ip_cadena, port_cadena);
//}
//
//
//
///*
// Este método nos permite recibir una imagen de la cámara del robot.
// 
// IMPORTANTE: Ha surgido el siguiente problema:
//    El sistema de coordenadas del "iphone" se situa en la esquina superior izquierda, no así
//    el sistema de "Quartz", la librería gráfica utilizada para pintar la información recibida.
// 
//    Se ha intentado hacer rotaciones a fin de conseguir poner la imagen tal y como se desea, no obstante
//    es necesario una rotación sobre un eje vertical (algo así como dar la vuelta al papel) que hasta ahora no se ha             
//    conseguido
//
// */
//
//
//- (IBAction)recibirImagen:(id)sender{
//    NSString *server_ip = ip.text;
//    NSString *server_port = puerto.text;
//    
//    //Forma de convertir NSString a char *
//    const char *ip_cadena = [server_ip UTF8String];
//    const char *port_cadena = [server_port UTF8String];
//    
//    char *buffer;    
//    buffer = askForImage(ip_cadena, port_cadena);
//
////                    int pixelsWide = 320;
////                    int pixelsHigh = 240;
////
////                    char* buffer = malloc(pixelsHigh*pixelsWide*3);
////                    
////                    if (buffer == NULL)
////                    {
////                        fprintf (stderr, "Memory not allocated!");
////                    }
////                    
////                    int size;
////                    for (int i=0; i<pixelsHigh*pixelsWide*3; i++) {
////                        //buffer[i] = rand()%256;
////                        buffer[i] = 0;
////                        size = i;
////                    }
////                    printf("buffer con tamaño %i",size);
//                        
//    //Quitamos la vista anterior de la pila de vistas
//    [self.subview removeFromSuperview];
//    
//    CGRect rect = CGRectMake(0,0,480,320);
//    self.subview = [[PruebaView alloc] initWithFrame:rect buf:buffer];
////    self.subview.alpha = 0.8;
//    [self.view insertSubview:self.subview atIndex:1];        
//
//    //Memory management
//    [self.subview autorelease];
//
//}
//
///*
// 
// Método para hacer que el robor acabe su movimiento
// La idea es hacer que cuando se levante el dedo de cualquiera de los
// botones de movimiento (andar, girar,...) se ejecute este metodo borrando
// los pasos restantes en la pila y haciendo que el robot detenga su  movimiento.
// 
// */
//
//- (IBAction)clearFootSteps:(id)sender{
//    NSLog(@"Se ha presionado el botón de clearFootSteps");
//    char * linea = "stop";
//    NSString *server_ip = ip.text;
//    NSString *server_port = puerto.text;
//        
//    //Forma de convertir NSString a char *
//    const char *ip_cadena = [server_ip UTF8String];
//    const char *port_cadena = [server_port UTF8String];
//    
//    sendMessage(linea,ip_cadena, port_cadena);
//}
//
//#pragma mark -
//
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //Actualizamos las variables globales
    if (textField == ip)
    {
        NSString *aux = [[NSString alloc]initWithString:textField.text];
        direccion_ip_host = aux;
        printf("El valor de la dirección ip del host es %s \n",aux);
    }
    else
    {
        NSString *aux = [[NSString alloc]initWithString:textField.text];
        puerto_host = aux;
        printf("El valor del puerto del host es %s \n",aux);
    }
    
	// the user pressed the "Done" button, so dismiss the keyboard	
    [textField resignFirstResponder];
	return YES;
    
}

///*
//  the touchesEnded method which will be called when touches are ended.
// */
//
//- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
//    
//    //Get all the touches.
//    NSSet *allTouches = [event allTouches];
//    
//    //Number of touches on the screen
//    switch ([allTouches count])
//    {
//        case 1:
//        {
//            //Get the first touch.
//            UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
//            
//            switch([touch tapCount])
//            {
//                case 1://Single tap
//                    NSLog(@"Toque simple");
//                    [self walkButton:self];
//                    break;
//                case 2://Double tap.
//                    NSLog(@"Doble toque");
//                    [self clearFootSteps:self];
//                    break;
//                case 3://Double tap.
//                    NSLog(@"Triple toque");
//                    break;
//                    
//            }
//        } 
//            break;
//    }
//    
//}
//
//#pragma mark -
//#pragma mark Video
//
//- (IBAction)videoButton:(id)sender{
//    
//    if (videoEstate == (int) VIDEO_OFF){
////        [video setEnabled:YES];
////        [video setTitle: @"Finalizar Video" forState: UIControlStateApplication];     
//        videoEstate = (int) VIDEO_ON;
//        NSThread* myThread = [[NSThread alloc] initWithTarget:self
//                                                     selector:@selector(videoMainRoutine)
//                                                       object:self];
//        [myThread start];  // Actually create the thread
//        
//        [myThread autorelease];                
//
//    }
//    else{
////        [video setHighlighted:NO];
////        [video setTitle: @"Empezar Video" forState: UIControlStateApplication];     
//        videoEstate = (int) VIDEO_OFF;
//    }
//}
//
//- (void)threadMainRoutine
//{
//        int i = 0;
//    while(videoEstate == (int) VIDEO_ON){
//        printf("Iteración %i \n",i);
//        i++;
//    }
//}
//
//
//-(void)videoMainRoutine
//{
//    NSString *server_ip = ip.text;
//    NSString *server_port = puerto.text;
//
//    //Forma de convertir NSString a char *
//    const char *ip_cadena = [server_ip UTF8String];
//    const char *port_cadena = [server_port UTF8String];
//    
//    int i = 1;
//
//    while(videoEstate == (int) VIDEO_ON){
//        
//        delay();
////        [NSThread sleepForTimeInterval:2];
//        char *buffer;
//        
//        printf("\n\nPeticion de imagen %i\n\n",i);
//        buffer = askForImage(ip_cadena, port_cadena);        
//        
//        printf("\n\nMostrado de imagen %i\n\n",i);
//        //Quitamos la vista anterior de la pila de vistas
//        [self.subview removeFromSuperview];
//        
//        CGRect rect = CGRectMake(0,0,480,320);
//        self.subview = [[PruebaView alloc] initWithFrame:rect buf:buffer];
//        //    self.subview.alpha = 0.8;
//        [self.view insertSubview:self.subview atIndex:1];        
//        
//        //Memory management
//        [self.subview release];
//        i++;        
//    }
//
//}

@end
